<?php
namespace app\client\controller;

use app\client\lib\SMS as AliSMS;

class Sms extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function merchantApply() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $request = request();
        
        $mobile = $request->post('mobile', 0, 'intval');
        $ip = $request->ip();
        
        return $this->_send($mobile, 'sms_merchant_apply_' . $this->userid, 'SMS_174991507');
    }
    
    public function agentApply() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $request = request();
        
        $mobile = $request->post('mobile', 0, 'intval');
        $ip = $request->ip();
        
        return $this->_send($mobile, 'sms_agent_apply_' . $this->userid, 'SMS_174986617');
    }
    
    
    private function _send($mobile, $key, $templateCode) {
        $sms = new AliSMS($mobile);
        $count = $sms->count();
        
        if($count > 10) {
            $sms->end();
            return errorResult('今天发送验证码的次数已用完');
        }
        
        $code = $sms->createCode();
        
        $rs = $sms->send($key, $code, 'iME爱迷', $templateCode, ['code' => $code]);
        $sms->end();
        
        if($rs['success']) {
            return successResult(['interval' => 60], '发送成功');
        }else{
            return errorResult($rs['msg']);
        }
    }
    
}